import React, { Component, Fragment } from 'react';
import StandardTable from '@/components/StandardTable';
import { Icon, Form, Input, Modal, Select, Row, Col, Upload, DatePicker } from 'antd';
import { connect } from 'dva';
import styles from '@/pages/Info.less';
import moment from 'moment';
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;
import AdButton from '@/components/AdButton';
import AntdInput from '@/components/AntdInput';
import { codes } from './utils';
const dateFormat = 'YYYY-MM-DD';

@connect(({ repair, loading, common }) => ({
  repair,
  loading: loading.models.repair,
  dictObject: common.dictObject,
}))
@Form.create()
export default class RepairInfo extends Component {
  state = {
    id: 0,
  };
  componentDidMount() {
    const { dispatch } = this.props;
    // 查询字典：
    //类型：
    dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'repair_details_type' },
    });
  }
  componentWillReceiveProps(nextProps) {
    const { data, id, dictObject } = nextProps;
    if (dictObject['repair_details_type'] && data.list) {
      dictObject['repair_details_type'].map(v => {
        data.list.map((v1, i1) => {
          if (v.code === v1.type) {
            data.list[i1].type = v.value;
          }
        });
      });
    }
  }

  columns = [
    {
      title: '数量',
      dataIndex: 'quantity',
      render: (text, record) =>
        this.props.type === 'list' ? (
          <AdButton
            mode="a"
            onClick={() => this.showDetail(record.id)}
            text={text}
            code={codes.showDetail}
          />
        ) : (
          <span>{text}</span>
        ),
    },
    {
      title: '编号',
      dataIndex: 'number',
    },
    {
      title: '类型',
      dataIndex: 'type',
    },
    {
      title: '名称',
      dataIndex: 'name',
    },

    {
      title: '金额',
      dataIndex: 'totalFee',
      render: text => {
        return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : ''}</span>;
      },
    },
    {
      title: '单价',
      dataIndex: 'repairTime',
      render: (text, record) => (
        <span>{(Number(record.totalFee) / Number(record.quantity)).toFixed(2)}</span>
      ),
    },
    {
      title: '品牌',
      dataIndex: 'brand',
    },
    {
      title: '质保期',
      dataIndex: 'assurancePeriod',
    },
    {
      title: '型号',
      dataIndex: 'repairModel',
    },
  ];

  // 显示详情
  showDetail = id => {
    const { showDetail, dispatch } = this.props;
    if (showDetail) showDetail();
    this.setState({ detailId: id });
    dispatch({
      type: 'repair/repairInfoDetail',
      payload: { id },
    });
  };

  // 新增或编辑操作
  handleOk = () => {
    const { form, dispatch, id, handleCancel } = this.props;
    const { detailId } = this.state;
    form.validateFields((err, value) => {
      if (err) {
        return;
      }
      const { assurancePeriod, ...values } = value;
      if (assurancePeriod) {
        values.assurancePeriod = moment(assurancePeriod).format(dateFormat);
      }
      if (detailId) {
        values.id = detailId;
      } else {
        values.repairId = id;
      }

      dispatch({
        type: 'repair/repairInfoOperate',
        payload: values,
        callback: res => {
          dispatch({
            type: 'repair/repairInfoList',
            payload: { id },
          });
          dispatch({
            type: 'repair/repairDetail',
            payload: { id },
          });
          form.resetFields();
          this.handleCancel();
        },
      });
    });
  };

  handleCancel = () => {
    const { handleCancel } = this.props;
    handleCancel();
    this.setState({ detailId: '' });
  };

  render() {
    const {
      loading,
      data,
      change,
      visible,
      handleCancel,
      form: { getFieldDecorator },
      id,
      type,
      repair: { infoDetail },
      dictObject,
    } = this.props;
    const { detailId } = this.state;
    const details = detailId ? infoDetail : {};

    const _gutter = { md: 4, lg: 12, xl: 24 };
    const _col = { md: 12, sm: 24 };

    return (
      <Fragment>
        <StandardTable
          loading={loading}
          data={data}
          disabledRowSelected={true}
          scrollX={500}
          columns={this.columns}
          onPaginationChange={change}
        />
        {visible && (
          <Modal
            title={detailId ? '编辑明细' : '新增明细'}
            visible={visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            width={620}
            style={{ top: 20 }}
            destroyOnClose={true}
          >
            <div className={styles.tableListForm}>
              <Form layout="inline">
                <Row gutter={_gutter}>
                  <Col {..._col}>
                    <Form.Item label="类型">
                      {getFieldDecorator('type', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: details.type || undefined,
                      })(
                        <Select placeholder="请选择" allowClear={true}>
                          {dictObject['repair_details_type'] &&
                            dictObject['repair_details_type'].map(item => (
                              <Option key={item.code}>{item.value}</Option>
                            ))}
                        </Select>
                      )}
                    </Form.Item>
                  </Col>
                  <Col {..._col}>
                    <Form.Item label="名称">
                      {getFieldDecorator('name', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: details.name || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={_gutter}>
                  <Col {..._col}>
                    <Form.Item label="数量">
                      {getFieldDecorator('quantity', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: details.quantity || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                  <Col {..._col}>
                    <Form.Item label="金额">
                      {getFieldDecorator('totalFee', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: details.totalFee || '',
                      })(
                        <AntdInput
                          mode="money"
                          label="金额"
                          placeholder="长度不超过18位可保留两位小数"
                          // addonBefore={prefixSelector()}
                        />
                      )}
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={_gutter}>
                  <Col {..._col}>
                    <Form.Item label="品牌">
                      {getFieldDecorator('brand', {
                        initialValue: details.brand || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                  <Col {..._col}>
                    <Form.Item label="编号">
                      {getFieldDecorator('number', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: details.number || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                </Row>
                <Row gutter={_gutter}>
                  <Col {..._col}>
                    <Form.Item label="质保期">
                      {getFieldDecorator('assurancePeriod', {
                        initialValue:
                          details && details.assurancePeriod
                            ? moment(details.assurancePeriod, dateFormat)
                            : null,
                      })(<DatePicker style={{ width: '100%' }} />)}
                    </Form.Item>
                  </Col>
                  <Col {..._col}>
                    <Form.Item label="型号">
                      {getFieldDecorator('repairModel', {
                        initialValue: details.repairModel || '',
                      })(<Input placeholder="请输入" />)}
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
          </Modal>
        )}
      </Fragment>
    );
  }
}
